// 全局变量
let currentMode = 'convert';
let currentPage = 1;
let totalPages = 1;
let pageSize = 10;
let abortController = new AbortController();

// DOM 加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    updateModeIndicator();
    loadHistory();

    // 事件监听
    document.getElementById('convertBtn').addEventListener('click', convertToHex);
    document.getElementById('translateBtn').addEventListener('click', translateFromHex);
    document.getElementById('pageSize').addEventListener('change', updatePageSize);
});

// 更新模式指示器
function updateModeIndicator() {
    const indicator = document.getElementById('modeIndicator');
    const inputField = document.getElementById('inputString');

    if (currentMode === 'convert') {
        indicator.className = 'mode-indicator mode-convert';
        indicator.textContent = '当前模式: 字符串转十六进制';
        inputField.placeholder = '请输入要转换的字符串...';
    } else {
        indicator.className = 'mode-indicator mode-translate';
        indicator.textContent = '当前模式: 十六进制转字符串';
        inputField.placeholder = '请输入要翻译的十六进制...';
    }
}

// 转换函数：字符串转十六进制
async function convertToHex() {
    currentMode = 'convert';
    updateModeIndicator();

    const inputString = document.getElementById('inputString').value.trim();
    const resultDiv = document.getElementById('result');

    if (!inputString) {
        resultDiv.innerHTML = '<p class="error-message">请输入要转换的字符串</p>';
        return;
    }

    resultDiv.innerHTML = '<div class="loader"></div>';

    try {
        // 取消之前的请求
        abortController.abort();
        abortController = new AbortController();

        const response = await fetch('/tool/tohex', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ input_string: inputString }),
            signal: abortController.signal
        });

        if (!response.ok) throw new Error('网络响应不正常');

        const data = await response.json();

        if (data.hex_string) {
            resultDiv.innerHTML = `
                <div class="result-content">
                    <p><strong>原始字符串:</strong> ${escapeHtml(inputString)}</p>
                    <p><strong>十六进制结果:</strong> ${escapeHtml(data.hex_string)}</p>
                </div>
                <button class="copy-btn" onclick="copyToClipboard('${escapeHtml(data.hex_string)}', event)">
                    复制结果
                </button>
                <span class="copy-message">已复制!</span>
            `;
            loadHistory();
        } else if (data.error) {
            throw new Error(data.error);
        }
    } catch (error) {
        if (error.name !== 'AbortError') {
            resultDiv.innerHTML = `<p class="error-message">错误: ${escapeHtml(error.message)}</p>`;
            console.error('转换错误:', error);
        }
    }
}

// 翻译函数：十六进制转字符串
async function translateFromHex() {
    currentMode = 'translate';
    updateModeIndicator();

    const inputHex = document.getElementById('inputString').value.trim();
    const resultDiv = document.getElementById('result');

    if (!inputHex) {
        resultDiv.innerHTML = '<p class="error-message">请输入要翻译的十六进制</p>';
        return;
    }

    resultDiv.innerHTML = '<div class="loader"></div>';

    try {
        // 取消之前的请求
        abortController.abort();
        abortController = new AbortController();

        const response = await fetch('/tool/translate', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ hex_string: inputHex }),
            signal: abortController.signal
        });

        if (!response.ok) throw new Error('网络响应不正常');

        const data = await response.json();

        if (data.translated_string) {
            const translatedWithBreaks = escapeHtml(data.translated_string).replace(/\n/g, '<br>');
            resultDiv.innerHTML = `
                <div class="result-content">
                    <p><strong>原始十六进制:</strong> ${escapeHtml(inputHex)}</p>
                    <p><strong>翻译结果:</strong> ${translatedWithBreaks}</p>
                </div>
                <button class="copy-btn" onclick="copyToClipboard('${escapeHtml(data.translated_string)}', event)">
                    复制结果
                </button>
                <span class="copy-message">已复制!</span>
            `;
            loadHistory();
        } else if (data.error) {
            throw new Error(data.error);
        }
    } catch (error) {
        if (error.name !== 'AbortError') {
            resultDiv.innerHTML = `<p class="error-message">错误: ${escapeHtml(error.message)}</p>`;
            console.error('翻译错误:', error);
        }
    }
}

// 加载历史记录
async function loadHistory(page = 1) {
    const historyList = document.getElementById('historyList');
    const paginationDiv = document.getElementById('pagination');

    // 显示加载状态
    historyList.innerHTML = '<div class="loader"></div>';
    paginationDiv.innerHTML = '';

    try {
        const response = await fetch(`/tool/history/?page=${page}&page_size=${pageSize}`);
        if (!response.ok) throw new Error('获取历史记录失败');

        const data = await response.json();

        // 更新分页信息
        currentPage = page;
        totalPages = Math.ceil(data.count / pageSize);

        // 渲染历史记录
        renderHistory(data.results);

        // 更新分页UI
        updatePaginationUI(data);

    } catch (error) {
        console.error('加载历史记录错误:', error);
        historyList.innerHTML = `<p class="error-message">加载失败: ${escapeHtml(error.message)}</p>`;
    }
}

// 渲染历史记录
function renderHistory(items) {
    const historyList = document.getElementById('historyList');

    if (items.length > 0) {
        let html = items.map(item => `
            <div class="history-item">
                <p><strong>${item.type === 'translate' ? '原始十六进制' : '原始字符串'}:</strong>
                   ${escapeHtml(item.original_string)}</p>
                <p><strong>${item.type === 'translate' ? '翻译结果' : '十六进制'}:</strong>
                   ${escapeHtml(item.result)}</p>
                <p><small>${new Date(item.created_at).toLocaleString()}</small></p>
                <div class="history-item-actions">
                    <button class="copy-btn" onclick="copyToClipboard('${escapeHtml(item.result)}', event)">
                        复制
                    </button>
                </div>
                <span class="copy-message">已复制!</span>
            </div>
        `).join('');

        historyList.innerHTML = html;
    } else {
        historyList.innerHTML = '<p class="no-history">暂无历史记录</p>';
    }
}

// 更新分页UI
function updatePaginationUI(data) {
    const paginationDiv = document.getElementById('pagination');
    paginationDiv.innerHTML = '';

    // 上一页按钮
    if (data.previous) {
        const prevBtn = document.createElement('button');
        prevBtn.textContent = '上一页';
        prevBtn.onclick = () => loadHistory(currentPage - 1);
        paginationDiv.appendChild(prevBtn);
    }

    // 页码信息
    const pageInfo = document.createElement('span');
    pageInfo.textContent = `第 ${currentPage} 页 / 共 ${totalPages} 页`;
    paginationDiv.appendChild(pageInfo);

    // 下一页按钮
    if (data.next) {
        const nextBtn = document.createElement('button');
        nextBtn.textContent = '下一页';
        nextBtn.onclick = () => loadHistory(currentPage + 1);
        paginationDiv.appendChild(nextBtn);
    }
}

// 更新每页条数
function updatePageSize() {
    pageSize = document.getElementById('pageSize').value;
    loadHistory(1); // 重置到第一页
}

// 复制到剪贴板
async function copyToClipboard(text, event) {
    try {
        await navigator.clipboard.writeText(text);
        showCopyMessage(event);
    } catch (err) {
        console.error('复制失败:', err);
        fallbackCopy(text, event);
    }
}

// 备用复制方法
function fallbackCopy(text, event) {
    const textarea = document.createElement('textarea');
    textarea.value = text;
    document.body.appendChild(textarea);
    textarea.select();

    try {
        const successful = document.execCommand('copy');
        if (successful) {
            showCopyMessage(event);
        } else {
            alert('复制失败，请手动选择文本后复制');
        }
    } catch (err) {
        console.error('复制失败:', err);
        alert('复制失败，请手动选择文本后复制');
    }

    document.body.removeChild(textarea);
}

// 显示复制成功消息
function showCopyMessage(event) {
    const message = event.target.nextElementSibling;
    if (message && message.classList.contains('copy-message')) {
        message.style.display = 'block';
        setTimeout(() => {
            message.style.display = 'none';
        }, 2000);
    }
}

// HTML转义函数
function escapeHtml(unsafe) {
    if (typeof unsafe !== 'string') return unsafe;
    return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}